#!/usr/bin/env python
# -*- coding:utf8 -*-
# uncompyle6 version 2.15.1
# Python bytecode 2.7 (62211)
# Decompiled from: Python 2.7.10 (default, Jul  1 2017, 13:36:56) 
# [GCC 4.4.6 20110731 (Red Hat 4.4.6-4)]
# Embedded file name: ./login/bkaccount/manager.py
# Compiled at: 2017-11-16 15:44:28
"""
Tencent is pleased to support the open source community by making 蓝鲸智云(BlueKing) available.
Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://opensource.org/licenses/MIT
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and limitations under the License.
"""
from django.db import models
from django.db.models import Q
from django.db import IntegrityError
from django.contrib.auth.models import BaseUserManager
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.conf import settings
from django.utils import timezone
from common.log import logger
from bkaccount.constants import RoleCodeEnum, ROLECODE_LIST, ApiErrorCodeEnum

class BkUserManager(BaseUserManager):
    """
    BK user manager
    """

    def _create_user(self, username, password, is_superuser, **extra_fields):
        """
        Create and saves a User with the given username and password
        """
        if not username:
            raise ValueError(u'请填写用户名')
        now = timezone.now()
        user = self.model(username=username, is_superuser=is_superuser, last_login=now, date_joined=now, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_user(self, username, password=None, **extra_fields):
        return self._create_user(username, password, False, **extra_fields)

    def create_superuser(self, username, password, **extra_fields):
        return self._create_user(username, password, True, **extra_fields)

    def _check_user_exist(self, username):
        """
        检查用户是否存在
        """
        try:
            user = self.get(username=username)
        except:
            return (
             False, None, u'用户名[%s]不存在' % username)

        return (True, user, '')

    def _get_user_info(self, user):
        return {'username': user.username,
           'chname': user.chname,
           'qq': user.qq,
           'phone': user.phone,
           'email': user.email,
           'role': str(user.role_code)
           }

    def get_user_info(self, username):
        """
        获取用户信息（结果，用户信息，错误信息）
        """
        is_exist, user, msg = self._check_user_exist(username)
        if not is_exist:
            return (False, {}, msg)
        return (True, self._get_user_info(user), '')

    def get_all_user(self, role):
        """
        获取所有用户
        """
        users = self.all()
        if role.isdigit() and int(role) in ROLECODE_LIST:
            users = users.filter(role__code=int(role))
        return [ self._get_user_info(user) for user in users ]

    def get_batch_user_with_dict(self, username_list):
        """
        批量获取用户，并以username为key的字典返回
        """
        data = {}
        users = self.filter(username__in=username_list)
        for user in users:
            data[user.username] = self._get_user_info(user)

        return data

    def modify_password_by_username(self, username, password):
        """
        修改用户密码(结果，错误类型，错误信息)
        """
        is_exist, user, msg = self._check_user_exist(username)
        if not is_exist:
            return (False, ApiErrorCodeEnum.USER_NOT_EXISTS, msg)
        try:
            user.set_password(password)
            user.save()
        except:
            msg = u'用户[%s]密码重置失败' % username
            logger.exception(msg)
            return (
             False, ApiErrorCodeEnum.USER_INFO_UPDATE_FAIL, msg)

        return (True, ApiErrorCodeEnum.SUCCESS, '')

    def modify_user_info(self, username, chname, qq, phone, email):
        """
        修改用户信息(结果，错误类型，错误信息)
        """
        is_exist, user, msg = self._check_user_exist(username)
        if not is_exist:
            return (False, ApiErrorCodeEnum.USER_NOT_EXISTS, msg)
        try:
            user.chname = chname
            user.qq = qq
            user.phone = phone
            user.email = email
            user.save()
        except:
            msg = u'个人[%s]信息修改失败' % username
            logger.exception(msg)
            return (
             False, ApiErrorCodeEnum.USER_INFO_UPDATE_FAIL, msg)

        return (True, ApiErrorCodeEnum.SUCCESS, '')

    def _modify_or_create_user_role(self, user, role_code):
        """
        修改或者添加用户角色
        """
        from bkaccount.models import BkUserRole, BkRole
        BkUserRole.objects.filter(user=user).delete()
        bkrole = BkRole.objects.get(code=role_code)
        BkUserRole.objects.create(user=user, role=bkrole)
        return True

    def modify_user_role(self, username, role):
        """
        修改用户角色
        """
        is_exist, user, msg = self._check_user_exist(username)
        if not is_exist:
            return (False, msg)
        if role in ROLECODE_LIST:
            if role != RoleCodeEnum.SUPERUSER and not self.exclude(id=user.id).filter(is_superuser=True).exists():
                return (False, u'账号为：%s 的用户是最后一个管理员，不可修改其角色' % username)
            user.is_superuser = role == RoleCodeEnum.SUPERUSER
            user.save()
            self._modify_or_create_user_role(user, role)
        return (True, '')

    def get_batch_user_with_paginator(self, page, page_size, search_username, search_data, search_role):
        """
        批量获取用户信息 并分页
        """
        if search_username:
            all_query = self.filter(username=search_username)
        else:
            all_query = self.all().order_by('-id')
        if search_role:
            all_query = all_query.filter(role__code=int(search_role))
        if search_data:
            all_query = all_query.filter(Q(username__icontains=search_data) | Q(chname__icontains=search_data))
        paginator = Paginator(all_query, page_size)
        try:
            records = paginator.page(page)
        except PageNotAnInteger:
            records = paginator.page(1)
        except EmptyPage:
            records = paginator.page(paginator.num_pages)

        return records

    def modify_or_create_user_by_userid(self, user_id, username, chname, qq, phone, email, role):
        """
        修改或者创建用户
        """
        try:
            if user_id and role != RoleCodeEnum.SUPERUSER:
                if not self.exclude(id=user_id).filter(is_superuser=True).exists():
                    return (False, user_id, u'账号为：%s 的用户是最后一个管理员，不可修改其角色' % username)
            if user_id:
                user = self.get(id=user_id)
                user.chname = chname
                user.qq = qq
                user.phone = phone
                user.email = email
                user.is_superuser = role == RoleCodeEnum.SUPERUSER
                user.save()
            else:
                user = self.create(username=username, chname=chname, qq=qq, phone=phone, email=email, is_superuser=role == RoleCodeEnum.SUPERUSER)
                user.set_password(settings.PASSWORD)
                user.save()
                user_id = user.id
            if role in ROLECODE_LIST:
                self._modify_or_create_user_role(user, role)
        except IntegrityError:
            return (
             False, user_id, u'账号为：%s 的用户已经存在' % username)
        except:
            logger.exception(u'保存用户信息(%s)出错' % username)
            return (
             False, user_id, u'保存用户信息(%s)出错' % username)

        return (True, user_id, '')

    def modify_or_create_user_by_username(self, username, chname, qq, phone, email):
        """
        通过username,修改或者创建用户
        """
        user, _c = self.get_or_create(username=username)
        user.chname = chname
        user.qq = qq
        user.phone = phone
        user.email = email
        if _c:
            user.is_superuser = False
            self._modify_or_create_user_role(user, RoleCodeEnum.STAFF)
            user.set_password(settings.PASSWORD)
        user.save()
        return True

    def delete_user(self, user_id, username):
        """
        删除用户
        """
        try:
            user = self.get(id=user_id)
            if user.username == 'admin':
                return (False, u'内置admin用户不可删除')
            if user.is_superuser and not self.exclude(id=user_id).filter(is_superuser=True).exists():
                return (False, u'最后一个管理员用户，不允许删除')
            self.filter(id=user_id).delete()
        except:
            logger.exception(u'用户(%s)删除失败' % username)
            return (
             False, u'用户(%s)删除失败' % username)

        return (True, '')

    def modify_password_by_userid(self, user_id, password):
        """
        修改用户密码(结果，错误类型，错误信息)
        """
        try:
            user = self.get(id=user_id)
            user.set_password(password)
            user.save()
        except:
            msg = u'用户密码重置失败'
            logger.exception(msg)
            return (
             False, msg)

        return (True, '')


class LoginLogManager(models.Manager):
    """
    User login log manager
    """

    def record_login(self, _user, _login_browser, _login_ip, host, app_id):
        try:
            self.model(user=_user, login_browser=_login_browser, login_ip=_login_ip, login_host=host, login_time=timezone.now(), app_id=app_id).save()
            return (
             True, u'记录成功')
        except:
            return (
             False, u'用户登录记录失败')
